<?php
namespace App\Http\Middleware\Auth\Owner\Trade;

use Closure;
use App\Core\Entity\Session\UserEntity;
use App\Services\Trade\Auth\DemandService;

/**
 * 数据拥有者检查
 */
class Demand
{

    /**
     * 用户实体
     *
     * @var \App\Core\Entity\Session\UserEntity
     */
    protected $user;

    /**
     * 求购服务
     *
     * @var \App\Services\Trade\Auth\DemandService
     */
    protected $service;

    /**
     * 初始化用户实体
     *
     * @param UserEntity $user            
     */
    public function __construct(UserEntity $user)
    {
        $this->user = $user;
        $this->service = new DemandService();
    }

    /**
     * 前置 | 后置
     *
     * @param \Illuminate\Http\Request $request            
     * @param \Closure $next            
     * @return \Closure $next
     */
    public function handle($request, Closure $next)
    {
        $id = $request->input('id');
        $userId = $this->user->getUserId();
        
        if ($id && ! $this->service->isOwner($id, $userId)) {
            abort(403);
        }
        
        return $next($request);
    }
}